package com.devops.admin.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.devops.admin.model.DOSExportDataJobLog;
import com.devops.admin.model.Pagination;
import com.devops.admin.model.TableResult;
import com.devops.admin.po.DOSExportDataJobLogPo;
import com.devops.admin.service.DOSExportDataJobLogService;
import com.devops.admin.mapper.DOSExportDataJobLogMapper;
import com.devops.admin.vo.DOSExportDataJobLogVo;
import com.devops.admin.vo.DOSPageVo;
import com.devops.admin.vo.ExportDataJobCallBack;
import com.devops.constant.ExportDataJobLogStatusEnum;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
* @author Dell
* @description 针对表【dos_export_data_job_log(导出数据任务记录)】的数据库操作Service实现
* @createDate 2023-12-25 16:39:19
*/
@Service
public class DOSExportDataJobLogServiceImpl extends ServiceImpl<DOSExportDataJobLogMapper, DOSExportDataJobLog>
    implements DOSExportDataJobLogService{

    @Override
    public TableResult<DOSExportDataJobLogPo> getExportDataJobLogList(DOSExportDataJobLogVo exportDataJobLogVo, DOSPageVo pageVo) {
        Page<DOSExportDataJobLogPo> page = new Page<>(pageVo.getPageNum(), pageVo.getPageSize());
        List<DOSExportDataJobLogPo> list = baseMapper.getExportDataJobLogList(exportDataJobLogVo, page);
        TableResult<DOSExportDataJobLogPo> tableResult = new TableResult<>();
        Pagination p = Pagination.builder().pageNum(page.getCurrent()).pageSize(page.getSize()).total(page.getTotal()).build();
        tableResult.setList(list);
        tableResult.setPagination(p);
        return tableResult;
    }

    @Override
    public void handleCallback(ExportDataJobCallBack callBack) {
        DOSExportDataJobLog jobLog = DOSExportDataJobLog.builder()
                .id(callBack.getLogId())
                .status(ExportDataJobLogStatusEnum.COMPLETED.getCode())
                .completedAt(LocalDateTime.now())
                .build();
        baseMapper.updateById(jobLog);
    }

    @Scheduled(cron = "0 0 0/1 * * ?")
    public void checkTimeoutExecutions() {
        lambdaQuery().eq(DOSExportDataJobLog::getStatus, ExportDataJobLogStatusEnum.IN_PROGRESS.getCode())
                .lt(DOSExportDataJobLog::getTriggerAt, DateUtil.offsetHour(new Date(), -1))
                .list()
                .forEach(jobLog -> {
                    DOSExportDataJobLog log = new DOSExportDataJobLog();
                    log.setId(jobLog.getId());
                    log.setStatus(ExportDataJobLogStatusEnum.FAILED.getCode());
                    updateById(log);
                });
    }
}




